package com.aivin.firplugin.httplib;

import com.aivin.firplugin.tool.WkLog;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class CountingOutputStream extends FilterOutputStream {

    private final ProgressListener listener;
    private long transferred;
    private long fileSize ;

    public CountingOutputStream(final OutputStream out,long fileSize , final ProgressListener listener) {
        super(out);
        this.listener = listener;
        this.fileSize = fileSize;
        this.transferred = 0;
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        out.write(b, off, len);
        this.transferred += len;
        setProgress(transferred);
    }

    @Override
    public void write(int b) throws IOException {
        out.write(b);
        this.transferred++;
        setProgress(transferred);
    }


    private void setProgress(long transferred){
        WkLog.showMsg("fileSize="+fileSize +"  transferred="+transferred);
        float progress = transferred /(fileSize* 1.0f)   ;
        progress = progress*100 ;
        listener.transferProgress(progress+"%");
    }
}
